package com.dongss.study.service;

import com.dongss.study.dao.RoleMenuAssignmentDAO;
import com.dongss.study.dao.UserDAO;
import com.dongss.study.domain.Menu;
import com.dongss.study.domain.RoleMenuAssignment;
import com.dongss.study.domain.User;
import com.dongss.study.domain.UserRoleAssignment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by dongshuanshuan on 17-7-30.
 */
@Service
@Transactional
public class RoleMenuAssignmentService {

    @Resource
    RoleMenuAssignmentDAO roleMenuAssignmentDAO;

    @Resource
    UserRoleAssignmentService userRoleAssignmentService;

    public Set<RoleMenuAssignment> findRoleMenusByUsername(String username){

        Set<RoleMenuAssignment> results=new HashSet<>();
        List<UserRoleAssignment> userRoleAssignments=userRoleAssignmentService.findUserRoleAssignmentsByUsername(username);

        for(UserRoleAssignment userRole:userRoleAssignments){
            Map<String,Object> params=new HashMap<>();
            params.put("role",userRole.getRole());
            List<RoleMenuAssignment> roleMenus=roleMenuAssignmentDAO.find("from RoleMenuAssignment assign where assign.role=:role",params);
            results.addAll(roleMenus);
        }
        return results;
    }

    public Set<Menu> findMenusByUsername(String username){

        Set<Menu> menus=new HashSet<>();
        Set<RoleMenuAssignment> roleMenus=findRoleMenusByUsername(username);
        for(RoleMenuAssignment roleMenu:roleMenus){
            menus.add(roleMenu.getMenu());
        }

        return menus;
    }

    public Set<String> findPermissionsByUsername(String username){
        Set<String> perms=new HashSet<>();
        Set<Menu> menus=findMenusByUsername(username);
        for(Menu menu:menus){
            if(menu.getPerms()!=null){
                perms.add(menu.getPerms());
            }

        }
        return perms;
    }

    public void create(RoleMenuAssignment roleMenu){
        roleMenuAssignmentDAO.save(roleMenu);
    }

    public void update(RoleMenuAssignment roleMenu){
        roleMenuAssignmentDAO.update(roleMenu);
    }

    public void delete(RoleMenuAssignment roleMenu){
        roleMenuAssignmentDAO.delete(roleMenu);
    }

    public RoleMenuAssignment find(Integer id){
        return roleMenuAssignmentDAO.get(id);
    }
}
